package com.medata.controller;

import com.google.gson.Gson;
import com.medata.dataObject.*;
import com.medata.exeptions.YunExceptions;
import com.medata.service.*;
import com.medata.utils.DataUtil;
import com.medata.utils.TimeUtil;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.hibernate.engine.spi.SessionImplementor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.*;

/**
 * @author ：zb
 * @date ：Created in 2019/7/10 0010 14:44
 * @description：
 */
@RestController
@RequestMapping("/port")
@Api
public class PortController {
    @Value("${solrPath}")
    private String solrPath;
    @Value("${FilePath}")
    private String filePath;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AccountService accountService;
    @Autowired
    private UserCollectionsService userCollectionsService;
    @Autowired
    private AdviceService adviceService;
    private HttpSolrServer solrServer;
    @Autowired
    private EntityManager entityManager;
    @Autowired
    private LogloginService logloginService;
    @Autowired
    private LogSearchService logSearchService;
    @Autowired
    private LogdetailService logdetailService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private HotWordsService hotWordsService;
    @Autowired
    private DocobjectService docobjectService;

    @RequestMapping(value = "/test",method = RequestMethod.GET)
    @ResponseBody
    public String test(){
        return "ok";
    }

    @RequestMapping(value = "/savehotwords", method = RequestMethod.POST)
    @ResponseBody
    public void savehotword(String word) {
        if (!word.equals("㓦")&&word.length()<5){
            HotWords HotWord = hotWordsService.findByHotWord(word);
            if (HotWord != null) {
                Integer hitCount = HotWord.getHitCount();
                hitCount++;
                HotWord.setHitCount(hitCount);
                hotWordsService.saveOrUpdate(HotWord);
            } else {
                HotWords hotWords = new HotWords();
                hotWords.setHotWord(word);
                hotWords.setHitCount(1);
                hotWordsService.saveOrUpdate(hotWords);
            }
        }
    }

    //预查询
    @RequestMapping(value = "/searchAdvance", method = RequestMethod.POST)
    @ResponseBody
    public List<String> getObjects(String doctitle, Integer page) {
        List<String> list = new ArrayList<>();
        if (doctitle != null && !doctitle.isEmpty()) {
            if (!doctitle.matches("[\\ssa-zA-Z]{1,}")) {
                solrServer = new HttpSolrServer(solrPath + "words");
                SolrQuery solrQuery = new SolrQuery();
                solrQuery.set("q", doctitle);
//                solrQuery.setSort("ID", SolrQuery.ORDER.asc);
                solrQuery.setStart(0);
                solrQuery.setRows(100000);
                //20190923:zb:此处排序无效
//                solrQuery.setSort("ID", SolrQuery.ORDER.asc);
                solrQuery.set("df", "word");
                solrQuery.set("fl", "word,pinyin,ID,varstr,tradstr");
                try {
                    QueryResponse response = solrServer.query(solrQuery);
                    SolrDocumentList results = response.getResults();
                    if (results != null && !results.isEmpty()) {
                        for (SolrDocument result : results) {
                            String title = (String) result.get("word");
                            if (title.startsWith(doctitle)) {
                                if ((result.get("varstr")) != null) {
                                    if ((result.get("tradstr")) != null) {
                                        title = title + ":" + (String) result.get("pinyin") + ":" + (String) result.get("ID") + ":" + (String) result.get("varstr") + ":" + (String) result.get("tradstr");
                                    } else {
                                        title = title + ":" + (String) result.get("pinyin") + ":" + (String) result.get("ID") + ":" + (String) result.get("varstr");
                                    }
                                } else if ((result.get("tradstr")) != null) {
                                    title = title + ":" + (String) result.get("pinyin") + ":" + (String) result.get("ID") + ":" + (String) result.get("tradstr");
                                }else{
                                    title = title + ":" + (String) result.get("pinyin") + ":" + (String) result.get("ID");
                                }
                                list.add(title);
                            }
                        }
                    }

                    //20190923:zb:手动增加排序,
                    list.sort(new Comparator<String>() {
                        @Override
                        public int compare(String o1, String o2) {
                            String s1=null;
                            String s2=null;
                            int i1 = StringUtils.countMatches(o1, ":");
                            int i2 = StringUtils.countMatches(o2, ":");
                            if (i1>2){
                                o1=o1.substring(0,o1.lastIndexOf(":"));
                            }
                            if (i2>2){
                                o2=o2.substring(0,o2.lastIndexOf(":"));
                            }
                            s1 = o1.substring(o1.lastIndexOf(":")+1);
                            s2 = o2.substring(o2.lastIndexOf(":")+1);
                            return Integer.valueOf(s1.trim())-Integer.valueOf(s2.trim());
                        }
                    });
                    if (page == null) {
                        if (list.size() > 0) {
                            if (list.size() > 8) {
                                list = list.subList(0, 8);
                            } else {
                                return list;
                            }
                        }
                    } else {
                        if (page != 9999) {
                            if (list.size() > 0) {
                                int size = list.size();
                                if (page * 10 > size) {
                                    list = list.subList((page - 1) * 10, size);
                                } else {
                                    list = list.subList((page - 1) * 10, page * 10);
                                }
                                list.add(String.valueOf(size));
                            }
                        }
                    }
//                    String lastStr=null;
//                    if (list.size()==11){
//                        lastStr = list.get(10);
//                        list.remove(10);
//                    }


//                    if (lastStr!=null){
//                        list.add(lastStr);
//                    }
                    return list;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                solrServer = new HttpSolrServer(solrPath + "dyx");
                SolrQuery solrQuery = new SolrQuery();
//                doctitle=doctitle.replaceAll(" ","*");
                solrQuery.set("q", doctitle);
//                solrQuery.setSort("engwords", SolrQuery.ORDER.asc);
                solrQuery.setStart(0);
                solrQuery.setRows(8);
                solrQuery.set("df", "engwords");
                solrQuery.set("fl", "engwords");
                try {
                    QueryResponse response = solrServer.query(solrQuery);
                    SolrDocumentList results = response.getResults();
                    if (results != null && !results.isEmpty()) {
                        for (SolrDocument result : results) {
                            Object title = result.get("engwords");
                            list.add(title.toString());
                        }
                    }
                    return list;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //查询
    @RequestMapping(value = "/searchWord", method = RequestMethod.POST)
    @ResponseBody
    public Object searchWord(Integer ID, HttpServletRequest request, String userName, String searchWords, String core, String returnWords, Integer page, String searchKey, Integer pagesize, String pronunciation) {
        solrServer = new HttpSolrServer(solrPath + core);
        SolrQuery query = new SolrQuery();
        if (searchWords.equals("㓦")){
            ID=2428;
        }
        if (ID != null && ID > 0) {
            query.set("q", ID);
            query.set("df", "ID");
        } else {
//            query.setQuery(searchKey + ":" + "\"" + searchWords + "\"");
            searchWords=ClientUtils.escapeQueryChars(searchWords);
            query.set("q",searchWords);
            query.set("df", searchKey);
        }
//        query.setSort("id",SolrQuery.ORDER.desc);
        query.setStart(page);
        if (pronunciation != null) {
            query.set("fq", "pinyin:" + pronunciation);
        }
        //20190923:zb:此处的排序有bug:增加排序后顺序存在bug可能和solr不同版本不同
//        query.setSort("id", SolrQuery.ORDER.desc);
        query.setRows(pagesize);
        query.set("fl", returnWords);
        try {
            QueryResponse response = solrServer.query(query);
            SolrDocumentList results = response.getResults();
            if (results != null && !results.isEmpty()) {
                SolrDocument result = results.get(0);
                //返回结果
                if ((result.get(searchKey)) != null && (result.get(searchKey)).equals(searchWords) && searchKey.equals("word")) {
                    //修改为包含即可
//              if ((result.get(searchKey)) != null && ((result.get(searchKey)).toString()).contains(searchWords) && searchKey.equals("word")) {
                    //记录查询

                    if (!searchKey.equals("ID")) {
                        LogSearch logSearch = new LogSearch();
                        logSearch.setActionId(300);
                        logSearch.setKeyword(searchWords);
                        if (userName != null) {
                            logSearch.setUsername(userName);
                        }
                        logSearch.setLogTime(Timestamp.valueOf(TimeUtil.getCurDate()));
                        logSearch.setResultcount(1);
                        logSearch.setUserip(request.getRemoteAddr());
                        logSearchService.save(logSearch);
                        //浏览日志
                        Logdetail logdetail = new Logdetail();
                        logdetail.setDoctitle(searchWords);
                        logdetail.setUserip(request.getRemoteAddr());
                        logdetail.setActionid("400");
                        if (userName != null) {
                            logdetail.setUsername(userName);
                        }
                        logdetail.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
                        logdetailService.save(logdetail);
                    }
                    return result;
                } else {
                    //记录查询
                    if (!searchKey.equals("ID")) {
                        LogSearch logSearch = new LogSearch();
                        logSearch.setActionId(300);
                        logSearch.setKeyword(searchWords);
                        if (userName != null) {
                            logSearch.setUsername(userName);
                        }
                        logSearch.setLogTime(Timestamp.valueOf(TimeUtil.getCurDate()));
                        logSearch.setResultcount(results.size());
                        logSearch.setUserip(request.getRemoteAddr());
                        logSearchService.save(logSearch);
                        //浏览日志
                        Logdetail logdetail = new Logdetail();
                        logdetail.setDoctitle(searchWords);
                        logdetail.setUserip(request.getRemoteAddr());
                        logdetail.setActionid("400");
                        if (userName != null) {
                            logdetail.setUsername(userName);
                        }
                        logdetail.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
                        logdetailService.save(logdetail);
                    }
                    return results;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //获取热词
    @RequestMapping(value = "/hotWordsGet", method = RequestMethod.GET)
    @ResponseBody
    public List<String> hotWordsGet() {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String results = ops.get("hotWords");
        if (results != null) {
            return DataUtil.getWords(results);
        }
        return null;
    }

    //获取新词
    @RequestMapping(value = "/newWordsGet", method = RequestMethod.GET)
    @ResponseBody
    public List<String> newWordsGet() {
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String results = ops.get("newWords");
        if (results != null) {
            return DataUtil.getWords(results);
        }
        return null;
    }

    //收藏词汇 0查询是否收藏1取消收藏2收藏3获取
    @RequestMapping(value = "/collectionsGet", method = RequestMethod.POST)
    @ResponseBody
    public Object colloctionsPut(String sortWord, Integer page, String userName, Integer searchType, String word, Integer wordId, String pronunciation) {
        if (word != null && word.length() > 0) {
            UserCollections result = userCollectionsService.findByUserNameAndWordAndWordId(userName, word, wordId);
            if (searchType == 0) {
                return result;
            } else if (searchType == 1) {
                if (result != null) {
                    userCollectionsService.deleteById(result.getId());
                }
            } else if (searchType == 2) {
                if (result == null) {
                    UserCollections userCollections = new UserCollections();
                    userCollections.setUserName(userName);
                    userCollections.setWord(word);
                    userCollections.setWordId(wordId);
                    pronunciation = pronunciation.replace("[", "");
                    pronunciation = pronunciation.replace("]", "");
                    userCollections.setPronunciation(pronunciation);
                    userCollections.setCreateTime(Timestamp.valueOf(TimeUtil.getCurDate()));
                    userCollectionsService.saveOrUpdate(userCollections);
                }
            }
        }
        if (searchType == 3) {
            Sort sort = new Sort(Sort.Direction.DESC, sortWord);
            Pageable pageable = new PageRequest(page - 1, 10, sort);
            Page<UserCollections> result = userCollectionsService.findByUserName(userName, pageable);
            int totalPages = result.getTotalPages();
            long count = result.getTotalElements();
            List<UserCollections> list = result.getContent();
            Map<String, String> map = new LinkedHashMap<>();
            map.put("totalPages", String.valueOf(totalPages));
            map.put("count", String.valueOf(count));
            for (UserCollections userCollections : list) {
                Timestamp createTime = userCollections.getCreateTime();
                String[] split = (createTime.toString()).split(" ");
                map.put(userCollections.getWordId() + "@$@" + userCollections.getWord(), userCollections.getPronunciation() + "$$$" + split[0]);
            }
            return map;
        }
        return null;
    }

    //注册和登入 0注册1登入
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public String register(HttpServletRequest request, String userName, String password, Integer type) {
        if (type == 0) {
            Account result = accountService.findByUserName(userName);
            if (result != null) {
                return "0";
            } else {
                Account account = new Account();
                account.setUserName(userName);
                account.setPassword(password);
                account.setTelephon(password);
                //true免费注册 false为注册后审核才能访问
                account.setStatus(true);
                account.setAddDateTime(Timestamp.valueOf(TimeUtil.getCurDate()));
                accountService.save(account);
            }
        } else if (type == 1) {
            Account account = accountService.findByUserName(userName);
            if (account == null || !account.getPassword().equals(password)) {
                return "0";
            }
            if (account.getStatus() != true) {
                return "0";
            }
            String ip = request.getRemoteAddr();
            Loglogin loglogin = new Loglogin();
            loglogin.setActionid(200);
            loglogin.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
            loglogin.setUsername(userName);
            loglogin.setUserip(ip);
            logloginService.save(loglogin);
            Loglogin log2 = new Loglogin();
            log2.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
            log2.setUsername(userName);
            log2.setUserip(ip);
            log2.setActionid(201);
            logloginService.save(log2);
        }
        return "1";
    }

    //搜索收藏的单词本
    @RequestMapping(value = "/collectionSearchWord4", method = RequestMethod.POST)
    @ResponseBody
    public Object collectionSearchWord4(String userName, String searchWord) {
        List<UserCollections> result = userCollectionsService.findByUserNameAndWord(userName, searchWord);
        Map<String, String> map = new LinkedHashMap<>();
        int size = result.size();
        int totalPages = size % 10 == 0 ? size / 10 : (size / 10) + 1;
        map.put("totalPages", String.valueOf(totalPages));
        map.put("count", String.valueOf(size));
        for (UserCollections userCollections : result) {
            Timestamp createTime = userCollections.getCreateTime();
            String[] split = (createTime.toString()).split(" ");
            map.put(userCollections.getWordId() + "@$@" + userCollections.getWord(), userCollections.getPronunciation() + "$$$" + split[0]);
        }
        return map;
    }

    //标注于略语 0获取榜单1获取对应的内容第n页
    @RequestMapping(value = "/labelsGet", method = RequestMethod.POST)
    @ResponseBody
    public Object labelsGet(String returnWords, String core, String searchKey, String searchWord, Integer page, Integer searchType) {
        Gson gson = new Gson();
        solrServer = new HttpSolrServer(solrPath + core);
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection con = session.connection();
        SolrQuery query = new SolrQuery();
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        if (searchType == 0) {
            String sql = "select * from " + searchKey;
            try {
                PreparedStatement ps = con.prepareStatement(sql);
                ResultSet resultSet = ps.executeQuery();
                while (resultSet.next()) {
                    String value = resultSet.getString(1);
                    String desc = resultSet.getString(2);
                    query.set("q", value);
                    query.set("df", searchKey);
                    query.setRows(0);
                    query.setStart(0);
                    QueryResponse response = solrServer.query(query, SolrRequest.METHOD.POST);
                    long numFound = response.getResults().getNumFound();
                    value = value + "(" + desc + ")";
                    map.put(value, String.valueOf(numFound));
                }
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                throw new YunExceptions(0, "获取标注榜单的时候出现bug");
            }
        } else if (searchType == 1) {
            query.set("fl", returnWords);
            query.set("q", searchWord);
            query.set("df", searchKey);
            Integer start = (page - 1) * 15;
            query.setStart(start);
            query.setRows(15);
            try {
                QueryResponse response = solrServer.query(query);
                SolrDocumentList results = response.getResults();
                if (results != null) {
                    int numFound = (int) results.getNumFound();
                    Integer totalPages = numFound % 20 == 0 ? numFound / 20 : (numFound / 20) + 1;
                    map.put("total", String.valueOf(numFound));
                    map.put("totalPages", String.valueOf(totalPages));
                    for (SolrDocument document : results) {
                        String engwords = (String) document.get("engwords");
                        String title = (String) document.get("DocTitle");
                        map.put(title, engwords);
                    }
                    return map;
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new YunExceptions(0, "获取百科页面的时候出现");
            }

        }
        return null;
    }

    //初始化拼音
    @RequestMapping(value = "/pronunciationGet", method = RequestMethod.POST)
    @ResponseBody
    public Object pronunciationGet() {
        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        Map<String, List<String>> map = new HashMap<>();
        for (char i = 'A'; i <= 'Z'; i++) {
            String searchKey = String.valueOf(i);
            String pronunciations = (String) ops.get("pronunciation", searchKey.toLowerCase());
            String[] split = pronunciations.split(",");
            List<String> list = new ArrayList<>();
            for (String str : split) {
                String[] values = str.split("=");
                list.add(values[0]);
            }
            map.put(searchKey, list);
        }
        return map;
    }

    //拼音搜索
    @RequestMapping(value = "/pronunciationSearch", method = RequestMethod.POST)
    @ResponseBody
    public Object pronunciationSearch(String letter, String searchWord) {
        HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
        String hvalue = (String) ops.get("pronunciation", letter.toLowerCase());
        String[] values = hvalue.split(",");
        for (String value : values) {
            value = value.replace("{", "");
            if (value.startsWith(searchWord)) {
                return value;
            }
        }
        return null;
    }

    //获取拓展词
    @RequestMapping(value = "/expandWordsGet", method = RequestMethod.POST)
    @ResponseBody
    public Object expandWordsGet(String userName, String searchWord, HttpServletRequest request) {
        HttpSolrServer solrServer = new HttpSolrServer(solrPath + "words");
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.set("q", searchWord);
        solrQuery.set("df", "DocTitle");
        solrQuery.set("fl", "DocTitle,pinyin");
        Map<String, String> map = new HashMap<>();
        try {
            QueryResponse response = solrServer.query(solrQuery);
            SolrDocumentList results = response.getResults();
            if (results != null) {
                for (int i = 0; i < results.size(); i++) {
                    SolrDocument x = results.get(i);
                    Object k = x.get("pinyin");
                    Object v = x.get("DocTitle");
                    map.put((String) k, (String) v);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new YunExceptions(0, "获取拓展词的时候出现bug");
        }
        //浏览日志
        Logdetail logdetail = new Logdetail();
        logdetail.setDoctitle(searchWord);
        logdetail.setUserip(request.getRemoteAddr());
        logdetail.setActionid("400");
        if (userName != null) {
            logdetail.setUsername(userName);
        }
        logdetail.setLogtime(Timestamp.valueOf(TimeUtil.getCurDate()));
        logdetailService.save(logdetail);
        return map;
    }

    //收取用户意见
    //获取建议
    @RequestMapping(value = "/advice", method = RequestMethod.POST)
    @ResponseBody
    public void advice(String user, String name, String email, String content) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        String sql = "insert into advice (userName,name,email,content,createTime) values ('" + user + "','" + name + "', '" + email + "','" + content + "','" + TimeUtil.getCurDate() + "')";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    //候选字收藏
    @RequestMapping(value = "/selectWordCollect", method = RequestMethod.POST)
    @ResponseBody
    public void selectWordCollect(String userName, String word, String pronunciation) {
        solrServer = new HttpSolrServer(solrPath + "words");
        SolrQuery query = new SolrQuery();
        query.set("q", word);
        query.set("df", "word");
        query.set("fl", "ID");
        query.set("fq", "pinyin:" + pronunciation);
        try {
            QueryResponse response = solrServer.query(query);
            SolrDocumentList results = response.getResults();
            if (results != null) {
                SolrDocument document = results.get(0);
                String IID = (String) document.get("ID");
                Integer id = Integer.valueOf(IID);
                UserCollections result = userCollectionsService.findByUserNameAndWordAndWordId(userName, word, id);
                if (result == null) {
                    UserCollections userCollections = new UserCollections();
                    userCollections.setUserName(userName);
                    userCollections.setWord(word);
                    userCollections.setWordId(id);
                    userCollections.setPronunciation(pronunciation);
                    userCollections.setCreateTime(Timestamp.valueOf(TimeUtil.getCurDate()));
                    userCollectionsService.saveOrUpdate(userCollections);
                }
            } else {
                throw new YunExceptions(0, "单词本收藏候选字差不多单词");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取投稿记录
    @RequestMapping(value = "/adviceGet", method = RequestMethod.POST)
    @ResponseBody
    public Object adviceGet(String userName, Integer page) {
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        Pageable pageable = new PageRequest(page - 1, 10);
        Page<Advice> result = adviceService.findByUserName(userName, pageable);
        List<Advice> list = result.getContent();
        String sql = "select count(*) from Advice where userName= ? ";
        try {
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setString(1,userName);
            ResultSet resultSet = ps.executeQuery();
            String totals = null;
            while (resultSet.next()) {
                totals = resultSet.getString(1);
            }
            Map<String, List<Advice>> map = new HashMap<>();
            map.put(totals, list);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //在线历史记录操作
    @RequestMapping(value = "/history", method = RequestMethod.POST)
    @ResponseBody
    public Object history(String pronunciation, String wordID, String word, Integer code, String userName, Integer page) {
        if (code == 0) {
            History history = new History();
            history.setCreateTime(TimeUtil.getCurDate());
            history.setUserName(userName);
            history.setWord(word);
            history.setWordID(wordID);
            history.setPronunciation(pronunciation);
            historyService.save(history);
        } else if (code == 1) {
            Pageable pageable = new PageRequest(page - 1, 10);
            Page<History> result = historyService.findByUserName(userName, pageable);
            List<History> list = result.getContent();
            String sql = "select count(*) from history where userName = ? ";
            SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
            Connection connection = session.connection();
            String totals = null;
            try {
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1,userName);
                ResultSet resultSet = ps.executeQuery();
                while (resultSet.next()) {
                    totals = resultSet.getString(1);
                }
                Map<String, List<History>> map = new HashMap<>();
                map.put(totals, list);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @RequestMapping(value = "/correct",method = RequestMethod.POST)
    @ResponseBody
    public void correct(String name,String word,String content){
        SessionImplementor session = entityManager.unwrap(SessionImplementor.class);
        Connection connection = session.connection();
        try {
            String sql="insert into corrects (name,word,content,subtime) values (?,?,?,?)";
            PreparedStatement pre = connection.prepareStatement(sql);
            pre.setString(1,name);
            pre.setString(2,word);
            pre.setString(3,content);
            String curDate = TimeUtil.getCurDate();
            pre.setString(4,curDate);
            pre.execute();
            connection.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequestMapping(value = "/docsGet",method = RequestMethod.POST)
    @ResponseBody
    public String docsGet(String likeStr){

        List<Docobject> docList = docobjectService.findByObjectfilenameLike("%"+likeStr+"%");
        docList.sort(new Comparator<Docobject>() {
            @Override
            public int compare(Docobject o1, Docobject o2) {
                Integer p1 = pathCompare(o1.getServerfullpath());
                Integer p2 = pathCompare(o2.getServerfullpath());
                return p1-p2;
            }
        });

        StringBuffer sb=new StringBuffer("");
        if (docList!=null){
            for (Docobject dc:docList){
                String path = "dyx"+ dc.getServerfullpath();
                sb.append(path+",");
            }
        }
        return sb.toString();
    };

    public static Integer pathCompare(String str){
        if (str.contains("small")){
            return 1;
        }else if (str.contains("bronze")){
            return 2;
        }else if (str.contains("oracle")){
            return 3;
        }
        return 4;
    }
}